<?php

namespace Modules\Admin\Http\Controllers\Admin;

use App\Exceptions\BusinessException;
use App\Helpers\CodeResponse;
use App\Helpers\QueryBuilder;
use App\Http\Controllers\Admin\ApiController;
use App\Http\Resources\BaseResource;
use Modules\Admin\Entities\Admin;
use Modules\Admin\Http\Requests\AdminRequest;
use Modules\Admin\Http\Requests\SyncPermissionRequest;
use Modules\Admin\Http\Requests\SyncRoleRequest;
use Modules\Admin\Services\AdminService;
use Modules\Admin\Services\PermissionService;

class AdminController extends ApiController
{
    public function index()
    {
        $admins = QueryBuilder::for(Admin::query()->with([
            'roles.permissions' => function ($query) {
                // 没有下级的权限才是真正对应路由的权限 有下级的通常为菜单
                $query->whereRaw('_rgt - _lft = ?', [1]);
            },
            'permissions' => function ($query) {
                // 没有下级的权限才是真正对应路由的权限 有下级的通常为菜单
                $query->whereRaw('_rgt - _lft = ?', [1]);
            }
        ]))->fields()
            ->filters()->includes(['roles.permissions'])->sorts()
            ->page();
        return $this->success(BaseResource::collection($admins));
    }

    public function show(Admin $admin)
    {
        $admin->load(['roles.permissions']);
        return $this->success($admin);
    }

    public function store(AdminRequest $request)
    {
        $admin = AdminService::getInstance()->Add($request->toArray());
        return $this->create($admin);
    }

    public function update(Admin $admin, AdminRequest $request)
    {
        $admin = AdminService::getInstance()->Update($admin, $request->toArray());
        return $this->success($admin);
    }

    public function assignRoles(Admin $admin, SyncRoleRequest $request)
    {
        if ($admin->super_admin) {
            throw new BusinessException(CodeResponse::PARAM_FAIL, "超级管理员无需分配角色！");
        }
        if (!$this->admin->super_admin && !$this->admin->hasAllRoles($request->get('roles'))) {
            throw new BusinessException(CodeResponse::PERMISSIONS_FAIL, "禁止分配您没有的角色给子管理员！");
        }
        $admin->syncRoles($request->get('roles'));
        return $this->create($admin);
    }

    public function assignPermissions(Admin $admin, SyncPermissionRequest $request)
    {
        if ($admin->super_admin) {
            throw new BusinessException(CodeResponse::PARAM_FAIL, "超级管理员无需分配权限！");
        }
        if (!$this->admin->super_admin && !$this->admin->hasAllPermissions($request->get('permissions'))) {
            throw new BusinessException(CodeResponse::PERMISSIONS_FAIL, "禁止分配您没有的权限给子管理员！");
        }

        $permissions = $request->get('permissions');
        $permissions = PermissionService::mergePermissionAncestors($permissions);
        $admin->syncPermissions($permissions);
        return $this->create($admin);
    }

    public function destroy(Admin $admin)
    {
        AdminService::getInstance()->Destroy($admin);
        return $this->noContent();
    }
}
